package com.hsmw.schedule.interceptor;

import com.google.common.util.concurrent.RateLimiter;
import com.hsmw.schedule.exception.ApiException;
import com.htn.common.core.constant.CommonConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 类名称：RateLimitInterceptor
 * 类描述：全局限流拦截器
 *
 * @author
 */
@Slf4j
@Component
public class RateLimitInterceptor implements HandlerInterceptor {

	/**
	 *
	 */
	private static final RateLimiter rateLimiter =
			RateLimiter.create(100);

	@Override
	public boolean preHandle(HttpServletRequest request,
							 HttpServletResponse response,
							 Object handler) {
		if (!rateLimiter.tryAcquire()) {
			log.error("系统已被限流...");
			throw new ApiException(CommonConstants.ResponseStatus.RATE_LIMIT_ERROR);
		}
		return true;
	}
}
